package com.foreknow.controller;

import com.foreknow.bean.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 创建一个LoginServlet来处理Login.html发送的请求
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在doPost中处理表单的数据
        //设置服务器端向客户端响应的内容的类型(MIME)   这一行代码是固定的 必须写的
//        resp.setContentType("text/html;charset=utf-8");
//        //设置客户端向服务器端请求的字符编码集为utf-8    必须写的
//        req.setCharacterEncoding("utf-8");
        //获取到Seeion
        HttpSession session = req.getSession();

        PrintWriter out = resp.getWriter();
        //如何才能获取到请求的参数 req.getParameter(String s)
        String username = req.getParameter("email");
        String password = req.getParameter("password");
        //需要调用Model(Service和Dao)
        AdminService service = new AdminServiceImpl();
        Admin admin = service.isValidate(username,password);
        if (admin!=null){
            session.setAttribute("username",admin.getUsername());
//            out.println("登录成功!!!");
//            跳转资源(转发)
            req.getRequestDispatcher("/user/manager?q=list").forward(req,resp);
            //重定向
//        resp.sendRedirect(req.getContextPath()+"/user/manager");

        }else{
            out.println("登录失败....");
        }
    }
}
